package game.games.gol;
import game.Abstract2DMap;
import game.AbstractGame;
import game.Point;
import game.Util;
import game.console.Console;
import game.console.IConsoleCommand;

import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.swing.SwingUtilities;


public class GameOfLife extends Abstract2DMap
{
    private static GameOfLife instance;
    
    public synchronized static GameOfLife getInstance()
    {
        if (instance == null)
        {
            instance = new GameOfLife();
            synchronized (instance)
            {
                for (IConsoleCommand commandObj : GameOfLifeCommands.getCommands())
                {
                    Console.getInstance().addConsoleCommand(commandObj);
                }
            }
        }
        return instance;
    }
    
    private List<Cell>      cells                = new ArrayList<Cell>();
    
    private int             generation           = 0;
    private int             livingCells          = 0;
    private int             livingCellsIdentical = 0;
    
    private GameOfLifeRules rule                 = GameOfLifeRules.DEFAULT;
    
    private Point           newSize              = null;
    private ColorSet        colorSet             = ColorSet.DEFAULT;
    private static boolean  CREATE_LIVE_MODE     = false;
    
    public void setRule(String rule)
    {
        try
        {
            GameOfLifeRules newRule = new GameOfLifeRules(rule);
            pause();
            this.rule = newRule;
            resume();
        }
        catch(Exception ex)
        {
            AbstractGame.log(ex);
        }
    }
    
    private Cell getCell(Point position)
    {
        return getCell((int) position.getWidth(), (int) position.getHeight());
    }
    
    public Cell getCell(int x, int y)
    {
        int index = calculateIndex(x, y);
        return cells.get(index);
    }
    
    private int nextLivingCells = 1500;
    
    public void setLivingCells(int livingCells)
    {
        if (livingCells > cells.size())
        {
            livingCells = cells.size();
        }
        this.nextLivingCells = livingCells;
    }
    
    public void setProzentLivingCells(int prozent)
    {
        if (prozent > 100)
        {
            livingCells = cells.size();
        }
        nextLivingCells = (cells.size() / 100) * prozent;
    }
    
    private void addLivingCells()
    {
        long startTime = System.nanoTime();
        if (isRunning() && isPaused() == false)
        {
            pause();
        }
        final List<Point> livingCells = Collections.synchronizedList(new ArrayList<Point>());
        
        int maxThreads = 8;
        Runnable randomLivingCellsThread = new Runnable()
        {
            @Override
            public void run()
            {
                // Lebende Zellen generieren
                Random RANDOM = new Random(System.nanoTime());
                do
                {
                    Point position = calculatePosition(RANDOM.nextInt(cells.size()));
                    if (position.getX() > 0 && position.getY() > 0 && livingCells.contains(position) == false)
                    {
                        livingCells.add(position);
                    }
                }
                while (livingCells.size() < nextLivingCells);
            }
        };
        List<Thread> threads = new ArrayList<Thread>();
        while(threads.size() < maxThreads)
        {
            Thread t = new Thread(randomLivingCellsThread, "RandomLivingCellsThread " + threads.size());
            t.start();
            threads.add(t);
        }
        for (Thread thread : threads)
        {
            while (thread.isAlive())
            {
                try
                {
                    thread.join();
                }
                catch (InterruptedException e)
                {
                    //
                }
            }
        }
        // reset count
        for (Point position : livingCells)
        {
            Cell cell = getCell(position);
            cell.setAlive(true);
            cell.setSurviving(true);
        }
        AbstractGame.log(livingCells.size() + " living cells added (" + Util.nanoToSec(System.nanoTime() - startTime) + " sec)");
        if (isRunning() && isPaused())
        {
            resume();
        }
    }
    
    @Override
    public void requestRestart()
    {
        Point newSize = GameOfLifeRunner.getInstance().calcMaxSize();
        if (newSize.equals(getSize()) == false)
        {
            AbstractGame.log("REQUEST RESTART size: " + (this.newSize = newSize));
        }
        super.requestRestart();
    }
    
    private void resetGeneration()
    {
        pause();
        long startTime = System.nanoTime();
        for (Iterator<Cell> i = cells.iterator(); i.hasNext();)
        {
            Cell cell = i.next();
            cell.setAlive(false);
            cell.setSurviving(false);
        }
        generation = 0;
        AbstractGame.log("resetGeneration() (" +  + Util.nanoToSec(System.nanoTime() - startTime)  + " sec)");
    }
    
    @Override
    protected void restart()
    {
        if (cells.isEmpty())
        {
            initGeneration(GameOfLifeRunner.getInstance().calcMaxSize());
        }
        else if (newSize != null && cells.size() != newSize.getSum())
        {
            initGeneration(newSize);
        }
        else if (cells.size() != getSize().getSum())
        {
            initGeneration(getSize());
        }
        else
        {
            resetGeneration();
            addLivingCells();
            start();
        }
    }
    
    private void initGeneration(Point xy)
    {
        // Anzahl Zellen
        long startTime = System.nanoTime();
        Point size = new Point(xy.getX(), xy.getY());
        setSize(size);
        int count = size.getSum();
        // Liste generieren
        if (cells.isEmpty() == false)
        {
            while (cells.size() > count)
            {
                cells.remove(cells.size() - 1);
            }
        }
        while (cells.size() < count)
        {
            cells.add(new Cell(false, false));
        }
        for (int i = 0; i < cells.size(); i++)
        {
            Cell cell = cells.get(i);
            Point position = calculatePosition(i);
            // RIGHT:
            Point RIGHT = new Point(position.getX(), position.getY());
            RIGHT.setX(RIGHT.getX() + 1);
            if (RIGHT.getX() >= size.getX())
            {
                RIGHT.setX(0);
            }
            cell.setRight(getCell(RIGHT));
            // BOTTOM:
            Point BOTTOM = new Point(position.getX(), position.getY());
            BOTTOM.setY(BOTTOM.getY() + 1);
            if (BOTTOM.getY() >= size.getY())
            {
                BOTTOM.setY(0);
            }
            cell.setBottom(getCell(BOTTOM));
            // LEFT:
            Point LEFT = new Point(position.getX(), position.getY());
            LEFT.setX(LEFT.getX() - 1);
            if (LEFT.getX() < 0)
            {
                LEFT.setX(size.getX() - 1);
            }
            cell.setLeft(getCell(LEFT));
            // TOP:
            Point TOP = new Point(position.getX(), position.getY());
            TOP.setY(TOP.getY() - 1);
            if (TOP.getY() < 0)
            {
                TOP.setY(size.getY() - 1);
            }
            cell.setTop(getCell(TOP));
            // BOTTOMLEFT:
            Point BOTTOMLEFT = new Point(position.getX(), position.getY());
            BOTTOMLEFT.setX(LEFT.getX());
            BOTTOMLEFT.setY(BOTTOM.getY());
            cell.setBottomLeft(getCell(BOTTOMLEFT));
            // BOTTOMRIGHT:
            Point BOTTOMRIGHT = new Point(position.getX(), position.getY());
            BOTTOMRIGHT.setX(RIGHT.getX());
            BOTTOMRIGHT.setY(BOTTOM.getY());
            cell.setBottomRight(getCell(BOTTOMRIGHT));
            // TOPLEFT:
            Point TOPLEFT = new Point(position.getX(), position.getY());
            TOPLEFT.setX(LEFT.getX());
            TOPLEFT.setY(TOP.getY());
            cell.setTopLeft(getCell(TOPLEFT));
            // TOPRIGHT:
            Point TOPRIGHT = new Point(position.getX(), position.getY());
            TOPRIGHT.setX(RIGHT.getX());
            TOPRIGHT.setY(TOP.getY());
            cell.setTopRight(getCell(TOPRIGHT));
        }
        AbstractGame.log("initGeneration(" + xy.getX() + "/" + xy.getY() + ") complete, " + cells.size() + " cells created (" +  + Util.nanoToSec(System.nanoTime() - startTime)  + " sec)");
        addLivingCells();
        generation = 0;
        start();
        newSize = null;
    }
    
    public void setColorSet(ColorSet colorSet)
    {
        this.colorSet = colorSet;
    }
    
    public ColorSet getColorSet()
    {
        return colorSet;
    }
    
    @Override
    public void render(Graphics g, int cellSize)
    {
        if (isRunning())
        {
            for (int i = 0; i < cells.size(); i++)
            {
                Cell cell = cells.get(i);
                g.setColor(colorSet.getColor(cell.isAlive(), cell.isSurviving()));
                Point position = calculatePosition(i);
                g.fillRect((int) position.getWidth() * cellSize, (int) position.getHeight() * cellSize, cellSize, cellSize);
                if (isRunning() && isPaused() == false)
                {
                    // next round
                    cell.setAlive(cell.isSurviving());
                }
            }
        }
    }
    
    @Override
    public void doNext()
    {
        generation++;
        int alive = 0;
        for (int i = 0; i < cells.size(); i++)
        {
            Cell cell = cells.get(i);
            int livingNeighbors = cell.countLivingNeighbors();
            cell.setSurviving(rule.isSurviving(cell.isAlive(), livingNeighbors));
            if (cell.isAlive())
            {
                alive++;
            }
        }
        if (alive == livingCells)
        {
            livingCellsIdentical++;
        }
        else
        {
            livingCellsIdentical = 0;
        }
        livingCells = alive;
        setStatus("Generation " + generation + "; " + livingCells + " Living Cells");
        if (livingCells <= 0)
        {
            AbstractGame.log("No more living cells");
            requestRestart();
        }
        else if (livingCellsIdentical > 50)
        {
            requestRestart();
        }
    }

    @Override
    public KeyListener getKeyboardControl()
    {
        return new KeyAdapter()
        {
            private boolean IGNORE_KEYBOARD       = false;
            
            @Override
            public void keyPressed(KeyEvent e)
            {
                if (IGNORE_KEYBOARD)
                {
                    e.consume();
                }
                else
                {
                    IGNORE_KEYBOARD = true;
                    final Console console = Console.getInstance();
                    if (console.isOpen() == false)
                    {
                        switch (e.getKeyCode())
                        {
                            case KeyEvent.VK_P:
                            {
                                if (instance.isRunning())
                                {
                                    if (instance.isPaused())
                                    {
                                        instance.resume();
                                    }
                                    else
                                    {
                                        instance.pause();
                                    }
                                }
                                break;
                            }
                            case KeyEvent.VK_S:
                            {
                                instance.requestStop();
                                break;
                            }
                            case KeyEvent.VK_R:
                            {
                                instance.requestRestart();
                                break;
                            }
                        }
                    }
                    IGNORE_KEYBOARD = false;
                }
            }
        };
    }

    @Override
    public MouseListener getMouseControl()
    {
        return new MouseAdapter()
        {
            private boolean IGNORE_MOUSE = false;
            
            @Override
            public void mouseClicked(MouseEvent e)
            {
                if (SwingUtilities.isRightMouseButton(e))
                {
                    CREATE_LIVE_MODE = CREATE_LIVE_MODE == false;
                    AbstractGame.log("CREATIVE_LIVE_MODE " + CREATE_LIVE_MODE);
                }
                else if (SwingUtilities.isLeftMouseButton(e))
                {
                    if (IGNORE_MOUSE == false)
                    {
                        IGNORE_MOUSE = true;
                        Point pos = GameOfLifeRunner.getInstance().calcCoord(e.getPoint());
                        Cell cell = GameOfLife.getInstance().getCell(pos.getX(), pos.getY());
                        cell.setSurviving(true);
                        IGNORE_MOUSE = false;
                    }
                }
            }
        };
    }
    
    @Override
    public MouseMotionListener getMouseMotionListener()
    {
        return new MouseMotionAdapter() 
        {
            @Override
            public void mouseMoved(MouseEvent e)
            {
                if (CREATE_LIVE_MODE)
                {
                    try
                    {
                        Point pos = GameOfLifeRunner.getInstance().calcCoord(e.getPoint());
                        Cell cell = GameOfLife.getInstance().getCell(pos.getX(), pos.getY());
                        cell.setSurviving(true);
                    }
                    catch(IllegalArgumentException ex)
                    {
                        // ignore
                    }
                }
            }
        };
    }

    public static class GameOfLifeRunner extends AbstractGame
    {
        private static GameOfLifeRunner instance;
        
        public synchronized static GameOfLifeRunner getInstance()
        {
            if (instance == null)
            {
                instance = new GameOfLifeRunner();
            }
            return instance;
        }
        
        protected GameOfLifeRunner()
        {
            super(GameOfLife.getInstance());
        }
        
        public static void main(String[] args)
        {
             Thread t = new Thread(GameOfLifeRunner.getInstance(), "GameOfLife");
             t.start();
        }
    }
}
